<template>
	<view class="upload-content" :style="gridStyle">
		<block v-for="(item, index) in imageList" :key="index">
			<view class="upload-item" :style="{width:itemw,height:itemh}">
				<!-- :src="item.filePath" -->
				<image class="upload-img" :src="item.filePath || item.src"  mode="aspectFill" @click="previewImage(index)"></image>
				<view class="upload-del-btn align-center justify-center" v-if="isEdit===true"
				@click="delImage(index)" 
				>
					<image class="img"
						src="/static/u-close.png"
						mode="aspectFill"
					/>	
				</view>
				<view class="upload-progress" v-if="item.progress < 100">{{item.progress}}%</view>
			</view>
		</block>
		<view class="upload-item upload-add-btn" :style="{width:itemw,height:itemh}" v-if="rduLength > 0 && isEdit===true" @click="chooseImage"></view>
	</view>
</template>

<script>
import config from '@/common/config'

export default {
	data() {
		return {
			imageList: [
				// {filePath:'https://tinypng.com/images/panda-chewing.png'},
				// {filePath:'https://tinypng.com/images/panda-chewing.png'},
				// {filePath:'https://tinypng.com/images/panda-chewing.png'},
				// {filePath:'https://tinypng.com/images/panda-chewing.png'},
				// {filePath:'https://tinypng.com/images/panda-chewing.png'},
			]
		};
	},
	props: {
		// url: {
		// 	type: String,
		// 	value: '' //上传接口地址
		// },
		isEdit:{
			type: Boolean,
			default: true //单次可选择的图片数量
		},
		itemw:{
			type: String,
			default: '180rpx' //单次可选择的图片数量
		},
		itemh:{
			type: String,
			default: '180rpx' //单次可选择的图片数量
		},
		itemc:{
			type: Number,
			default: 3
		},
		itemgap:{
			type: String,
			default: '20rpx',
		},
		count: {
			type: Number,
			default: 9 //单次可选择的图片数量
		},
		length: {
			type: Number,
			value: 9 //可上传总数量
		}
	},
	computed: {
		rduLength(){
			return this.length - this.imageList.length;
		},
		gridStyle(){
			return {
				'grid-template-columns':'repeat('+this.itemc+',1fr)',
				// 'grid-column-gap': this.itemgap,
				'grid-row-gap': this.itemgap,
			}
		}
	},
	methods: {
		//选择图片
		chooseImage: function(){
			uni.chooseImage({
				count: this.rduLength < this.count ? this.rduLength : this.count, //最多可以选择的图片张数，默认9
				sizeType: ['original', 'compressed'], //original 原图，compressed 压缩图，默认二者都有
				sourceType: ['album','camera'], //album 从相册选图，camera 使用相机，默认二者都有
				success: (res)=> {
					const images = res.tempFilePaths;
					this.uploadFiles(images);
				}
			});
		},
		//上传图片
		async uploadFiles(images){
			this.imageList.push({
				filePath: images[0],
				progress: 0
			});
			uni.showLoading({
				title: '请稍后..',
				mask: true,
			})
		    try{
				const uploadUrl = await this.uploadImage(images[0]);
				if(uploadUrl !== false){
					images.splice(0, 1);
					this.imageList[this.imageList.length - 1].src = uploadUrl;
				
					//判断是否需要继续上传
					if(images.length > 0 && this.rduLength > 0){
						this.uploadFiles(images);
					}else{
						uni.hideLoading();
					}
				}
			}catch(err){
				//上传失败处理
				this.imageList.pop();
				uni.hideLoading();
				uni.showToast({
					title: '上传中出现问题，已终止上传',
					icon: 'none',
					mask: true,
					duration: 2000
				});
			}
			// }catch(err){
			// 	console.log(err);
			// 	uni.hideLoading();
			// 	uni.showToast({
			// 		title: '上传中出现问题，已终止上传',
			// 		icon: 'none',
			// 		mask: true,
			// 		duration: 2000
			// 	});
			// 	return;
			// }
		},
		uploadImage: function(file){
			return new Promise((resolve, reject)=> {
				//发送给后端的附加参数
				let token=uni.getStorageSync('token') || '';
				const formData = {
					// thumb_mode: 1,
					token
				};
				this.uploadTask = uni.uploadFile({
					url: config.uploadImgUrl, 
					filePath: file,
					name: 'file',
					formData: formData,
					success(uploadFileResult){
						console.log('success----',uploadFileResult)
						const uploadFileRes = JSON.parse(uploadFileResult.data) || {};
						//console.log("上传成功uploadFileRes---",uploadFileRes);
						if(uploadFileRes.code === 1 && uploadFileRes.data){
							//uploadFileRes.data.fullurl,url
							resolve(uploadFileRes.data.fullurl);
						}else{
							reject('接口返回错误');
						}
					}, 
					fail(err){
						console.log('err----',err);
						reject('网络链接错误');
					}
				});
				//上传进度
				this.uploadTask.onProgressUpdate((progressRes)=> {
					this.imageList[this.imageList.length - 1].progress = progressRes.progress;
				});
			});
		},
		//删除图片
		delImage: function(index){
			uni.showModal({
				content: '确定要放弃这张图片么？',
				success: (confirmRes)=> {
					if (confirmRes.confirm) {
						this.imageList.splice(index, 1);
					} 
				}
			});
		},
		//预览图片
		previewImage: function(index){
			const urls = [];
			this.imageList.forEach((item)=> {
				urls.push(item.filePath || item.src);
			})
			uni.previewImage({
				current: urls[index],
				urls: urls,
				indicator: "number"
			})
		},
	    //父组件获imageList
		getImgs(){
			return this.imageList.map(item=>item.src);
		},
		//父组件设置imageList
		setImgs(imgsArr){	
			console.log("setImgs===",imgsArr)
			this.imageList= imgsArr.map(i=>{
				return {
					src: i,
					progress: 100
				}
			})
			console.log("this.imageList===",this.imageList)
		},
	}
}
</script>

<style lang="scss">
	.upload-content{
		overflow:hidden;
		padding: 20rpx 0 0;
		display: grid;
	}
	.upload-item{
		position: relative;
		// float:left;
		// width:180rpx;
		// height:180rpx;
		// margin-right:20rpx;
		// margin-bottom:20rpx;
		
		// &:nth-child(3n){
		// 	margin-right:0;
		// }
		.upload-img{
			width:100%;
			height:100%;
			border-radius:8upx;
		}
		.upload-del-btn{
			position: absolute;
			right:-16upx;
			top:-30upx;
			// border: 4upx solid #fff;
			border-radius: 100px;
			padding: 20rpx;
			.img{
				width:36upx;
			    height:36upx;
			}
		}
		.upload-progress{
			position: absolute;
			left:0;
			top:0;
			display:flex;
			align-items:center;
			justify-content: center;
			width:100%;
			height:100%;
			background-color: rgba(0,0,0,.4);
			color:#fff;
			font-size:24upx;
			border-radius:8upx;
		}
	}
	.upload-add-btn {
		position: relative;
		float:left;
		// width:180rpx;
		// height:180rpx;
		z-index: 99;
		border-radius:8upx;
		// background:#EEEEEE;
		border: 2rpx solid #eee;
		&:before,
		&:after {
			content: " ";
			position: absolute;
			top: 50%;
			left: 50%;
			-webkit-transform: translate(-50%, -50%);
			transform: translate(-50%, -50%);
			width: 4upx;
			height: 60upx;
			background-color: #d6d6d6;
		}
		&:after {
			width: 60upx;
			height: 4upx;
		}
		&:active {
			background-color: #f7f7f7;
		}
	}

</style>
